using System;
using System.Collections;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Text;
using System.Windows.Forms;
using ctsu.Data;

namespace ctsu.Admin.Forms.CoreLab
{
	public class ImportNano : System.Windows.Forms.Form
	{
		private string _currentFile;
		private ArrayList _al;
		private ArrayList _alLines;
		private System.Windows.Forms.Label label1;
		private System.Windows.Forms.TextBox txtFile;
		private System.Windows.Forms.Button button1;
		private System.Windows.Forms.OpenFileDialog ofdlg;
		private System.Windows.Forms.Button btnImport;
		private System.Windows.Forms.Button btnClose;
		private System.Windows.Forms.Label label2;
		private System.Windows.Forms.TextBox txtResults;
		private System.Windows.Forms.Button btnPrint;
		private System.Windows.Forms.Button btnSave;
		private System.Windows.Forms.SaveFileDialog sfdlg;
		private System.ComponentModel.Container components = null;

		private PrintDialog _pDlg;
		private PrintDocument _pDoc;
		private int _page;
		private int _startRow;

		public ImportNano()
		{
			InitializeComponent();
		}


		protected override void Dispose(bool disposing)
		{
			if (disposing)
			{
				if (components != null)
				{
					components.Dispose();
				}
			}
			base.Dispose(disposing);
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.label1 = new System.Windows.Forms.Label();
			this.txtFile = new System.Windows.Forms.TextBox();
			this.button1 = new System.Windows.Forms.Button();
			this.ofdlg = new System.Windows.Forms.OpenFileDialog();
			this.btnImport = new System.Windows.Forms.Button();
			this.btnClose = new System.Windows.Forms.Button();
			this.txtResults = new System.Windows.Forms.TextBox();
			this.label2 = new System.Windows.Forms.Label();
			this.btnPrint = new System.Windows.Forms.Button();
			this.btnSave = new System.Windows.Forms.Button();
			this.sfdlg = new System.Windows.Forms.SaveFileDialog();
			this.SuspendLayout();
			// 
			// label1
			// 
			this.label1.Location = new System.Drawing.Point(8, 16);
			this.label1.Name = "label1";
			this.label1.Size = new System.Drawing.Size(96, 16);
			this.label1.TabIndex = 0;
			this.label1.Text = "Enter import file:";
			// 
			// txtFile
			// 
			this.txtFile.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
				| System.Windows.Forms.AnchorStyles.Right)));
			this.txtFile.Location = new System.Drawing.Point(88, 16);
			this.txtFile.Name = "txtFile";
			this.txtFile.Size = new System.Drawing.Size(488, 20);
			this.txtFile.TabIndex = 1;
			this.txtFile.Text = "";
			// 
			// button1
			// 
			this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
			this.button1.Location = new System.Drawing.Point(576, 16);
			this.button1.Name = "button1";
			this.button1.TabIndex = 2;
			this.button1.Text = "Browse...";
			this.button1.Click += new System.EventHandler(this.button1_Click);
			// 
			// btnImport
			// 
			this.btnImport.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
			this.btnImport.Enabled = false;
			this.btnImport.Location = new System.Drawing.Point(576, 48);
			this.btnImport.Name = "btnImport";
			this.btnImport.TabIndex = 3;
			this.btnImport.Text = "Import File";
			this.btnImport.Click += new System.EventHandler(this.btnImport_Click);
			// 
			// btnClose
			// 
			this.btnClose.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
			this.btnClose.Location = new System.Drawing.Point(323, 440);
			this.btnClose.Name = "btnClose";
			this.btnClose.TabIndex = 4;
			this.btnClose.Text = "Close";
			this.btnClose.Click += new System.EventHandler(this.btnClose_Click);
			// 
			// txtResults
			// 
			this.txtResults.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
				| System.Windows.Forms.AnchorStyles.Left)
				| System.Windows.Forms.AnchorStyles.Right)));
			this.txtResults.Location = new System.Drawing.Point(8, 80);
			this.txtResults.Multiline = true;
			this.txtResults.Name = "txtResults";
			this.txtResults.ScrollBars = System.Windows.Forms.ScrollBars.Both;
			this.txtResults.Size = new System.Drawing.Size(640, 352);
			this.txtResults.TabIndex = 5;
			this.txtResults.Text = "";
			// 
			// label2
			// 
			this.label2.Location = new System.Drawing.Point(8, 64);
			this.label2.Name = "label2";
			this.label2.Size = new System.Drawing.Size(100, 16);
			this.label2.TabIndex = 6;
			this.label2.Text = "Update Results:";
			// 
			// btnPrint
			// 
			this.btnPrint.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
			this.btnPrint.Location = new System.Drawing.Point(235, 440);
			this.btnPrint.Name = "btnPrint";
			this.btnPrint.TabIndex = 7;
			this.btnPrint.Text = "Print";
			this.btnPrint.Click += new System.EventHandler(this.btnPrint_Click);
			// 
			// btnSave
			// 
			this.btnSave.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
			this.btnSave.Location = new System.Drawing.Point(147, 440);
			this.btnSave.Name = "btnSave";
			this.btnSave.TabIndex = 8;
			this.btnSave.Text = "Save File";
			this.btnSave.Click += new System.EventHandler(this.btnSave_Click);
			// 
			// ImportNano
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
			this.ClientSize = new System.Drawing.Size(656, 470);
			this.Controls.Add(this.btnSave);
			this.Controls.Add(this.btnPrint);
			this.Controls.Add(this.label2);
			this.Controls.Add(this.txtResults);
			this.Controls.Add(this.txtFile);
			this.Controls.Add(this.btnClose);
			this.Controls.Add(this.btnImport);
			this.Controls.Add(this.button1);
			this.Controls.Add(this.label1);
			this.Name = "ImportNano";
			this.Text = "Import Nano Results";
			this.Load += new System.EventHandler(this.ImportNano_Load);
			this.ResumeLayout(false);

		}
		#endregion

		private void button1_Click(object sender, System.EventArgs e)
		{
			ofdlg.ShowDialog();
			txtFile.Text = ofdlg.FileName;
			if (txtFile.Text.Length > 0)
				btnImport.Enabled = true;
		}

		private void btnImport_Click(object sender, System.EventArgs e)
		{
			btnImport.Enabled = false;
			Cursor.Current = Cursors.WaitCursor;
			if (ImportFile())
			{
				UpdateResults();
				ShowResults();
			}
		}

		private void ShowResults()
		{

		}

		private bool ImportFile()
		{
			if (txtFile.Text.Length == 0)
				return false;
			_al = new ArrayList();

			StreamReader sr = null;
			string line;
			string[] aLine;
			string id;
			string result;
			int pos;
			bool isSample = false;
			try
			{
				sr = new StreamReader(txtFile.Text);
				while ((line = sr.ReadLine()) != null)
				{
					if (!isSample)
					{
						if (line.StartsWith("Sample ID"))
							isSample = true;
						continue;
					}

					//make sure we don't pick up a junk last line
					if (line.Length < 100)
						continue;

					aLine = line.Split('\t');
					id = aLine[0];
					if (id == "te")
						continue;

					pos = id.IndexOf(" ");
					if (pos > -1)
						id = id.Substring(0, pos);

					result = aLine[4].Trim();
					if (result.Length > 0)
						result += " ng/ul";

					NameVal nv = new NameVal();
					nv.StringValue = result;
					nv.Name = id;
					_al.Add(nv);
				}
				return true;

			}
			catch (Exception ex)
			{
				MessageBox.Show(this, ex.Message, "Import Error");
				return false;
			}
			finally
			{
				if (sr != null)
					sr.Close();
			}
		}

		private void UpdateResults()
		{
			_alLines = new ArrayList();
			string file = Path.GetFileNameWithoutExtension(txtFile.Text);
			string path = Application.StartupPath;
			path += @"\ImportFiles\";
			string pathFile = path + file + ".txt";


			int count = 1;
			while (File.Exists(pathFile))
			{
				count++;
				pathFile = path + file + "(" + count + ")" + ".txt";
			}

			_currentFile = pathFile;
			StreamWriter sw = null;
			try
			{
				sw = new StreamWriter(pathFile, false);

				if (_al.Count == 0)
				{
					MessageBox.Show(this, "There are no results to update!");
					return;
				}

				string result;
				foreach (NameVal nv in _al)
				{
					Application.DoEvents();
					if (IsDupe(nv.Name))
					{
						result = "***ID: " + nv.Name + " is listed two or more times in this file";
						sw.WriteLine(result);
						_alLines.Add(result);
						txtResults.Text += Environment.NewLine + result;

						continue;
					}

					result = UpdateResult(nv);
					_alLines.Add(result);
					sw.WriteLine(result);
					txtResults.Text += Environment.NewLine + result;
				}
			}
			catch (Exception ex)
			{
				MessageBox.Show(this, ex.Message, "Update Error");

				return;
			}
			finally
			{
				if (sw != null)
				{
					sw.Flush();
					sw.Close();
				}
			}
		}

		private bool IsDupe(string id)
		{
			int count = 0;
			foreach (NameVal nv in _al)
			{
				if (nv.Name == id)
				{
					count++;
					if (count > 1)
						return true;
				}
			}
			return false;
		}

		private string UpdateResult(NameVal nv)
		{
			string resultLine = "";

			int id = 0;
			int batch = 0;
			string result = "";
			string note = "";
			string existingResult = "";

			try
			{
				id = int.Parse(nv.Name);
			}
			catch
			{
				return "***Invalid ID: " + nv.Name;
			}

			result = nv.StringValue;
			if (result.Length == 0)
			{
				return "***No Result in nano file: ID: " + nv.Name;
			}

			if (!CheckSampleID(id, out resultLine, out batch, out note, out existingResult))
				return resultLine;

			if (existingResult.Length > 0)
				result = existingResult + "; " + result;

			UpdateSampleID(id, result, out resultLine, batch, note);
			return resultLine;
		}

		private void UpdateSampleID(int id, string result, out string message, int batch, string note)
		{
			message = "";
			string sql = "UPDATE TestSamples SET Result=@Result, Note=@Note WHERE ID=" + id;
			SqlConnection conn = DataAccess.GetSqlConnection();
			SqlCommand cmd = new SqlCommand(sql, conn);
			SqlParameter param = new SqlParameter("@Result", result);
			cmd.Parameters.Add(param);
			note = "Result from nano import on " + DateTime.Today.ToShortDateString() + " - " + note;
			param = new SqlParameter("@Note", note);
			cmd.Parameters.Add(param);

			try
			{
				conn.Open();
				int iRetVal = cmd.ExecuteNonQuery();
				if (iRetVal == 1)
				{
					message = "UPDATED - ID: " + id + " with result: " + result + "  (Out Batch: " + batch + ")";
					return;
				}
				message = "***Update failed for ID: " + id;

			}
			catch (Exception ex)
			{
				message = "***Error updating ID: " + id + "Error message: " + ex.Message;
			}
			finally
			{
				conn.Dispose();
			}

		}

		private bool CheckSampleID(int id, out string message, out int batchnum, out string note, out string existingResult)
		{
			message = "";
			note = "";
			batchnum = 0;
			existingResult = "";

			string sql = "SELECT BatchOutNum, Result, Note FROM TestSamples WHERE ID=" + id;
			SqlConnection conn = DataAccess.GetSqlConnection();
			SqlCommand cmd = new SqlCommand(sql, conn);
			SqlDataReader rdr = null;

			string sval = "";
			try
			{
				conn.Open();
				rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
				if (rdr.Read())
				{
					//if batchout is null then it has not been checked out
					if (rdr.IsDBNull(0))
					{
						message = "***ID: " + id + " is not checked out";
						return false;
					}
					batchnum = rdr.GetInt32(0);

					//get the note contents - this will be added to when updated
					if (!rdr.IsDBNull(2))
						note = rdr.GetString(2);

					if (rdr.IsDBNull(1))
						return true;

					sval = rdr.GetString(1);
					if (sval.Length > 0)
					{
						if (sval.ToLower().IndexOf("done") > -1)
						{
							existingResult = sval;
						}
						else
						{
							message = "***ID: " + id + " currently has a result (" + sval + ")";
							return false;
						}
					}
				}
				else
				{
					message = "***Could no find ID: " + id;
					return false;
				}
				return true;

			}
			catch (Exception ex)
			{
				message = "***Error looking up ID: " + id + ex.Message;
				return false;
			}
			finally
			{
				if (!rdr.IsClosed)
					rdr.Close();
				conn.Dispose();
			}
		}

		private void btnClose_Click(object sender, System.EventArgs e)
		{
			this.Close();
		}

		private void ImportNano_Load(object sender, System.EventArgs e)
		{

		}

		private void btnSave_Click(object sender, System.EventArgs e)
		{
			string file = Path.GetFileName(_currentFile);
			sfdlg.FileName = file;
			sfdlg.ShowDialog(this);

			StreamReader sr = new StreamReader(_currentFile);
			string sFile = sr.ReadToEnd();
			sr.Close();

			StreamWriter sw = new StreamWriter(sfdlg.FileName);
			sw.Write(sFile);
			sw.Flush();
			sw.Close();
		}

		private void btnPrint_Click(object sender, System.EventArgs e)
		{
			this._pDoc = new PrintDocument();
			//this._pDoc.DefaultPageSettings.Landscape = true;
			this._pDlg = new PrintDialog();
			this._pDlg.Document = this._pDoc;

			if (this._pDlg.ShowDialog(this) == DialogResult.Cancel)
				return;

			Cursor.Current = Cursors.WaitCursor;
			this._pDoc.PrintPage += new PrintPageEventHandler(_pDoc_PrintPage);
			_page = 1;
			_pDoc.Print();
			_startRow = 0;
		}

		private void _pDoc_PrintPage(object sender, PrintPageEventArgs e)
		{
			StringBuilder sb = new StringBuilder();
			Graphics gfx = e.Graphics;
			float pageBottom = gfx.VisibleClipBounds.Height;
			float pageWidth = gfx.VisibleClipBounds.Width;
			float leftMargin = 50;
			float topMargin = 50;

			Font prntFont = new Font("Arial", 10);
			Font titleFont = new Font("Arial", 14, FontStyle.Bold);
			Font subTitleFont = new Font("Arial", 12);
			Font ColumnHeadFont = new Font("Arial", 10, FontStyle.Bold);

			Pen pen = new Pen(Color.Black);

			//get the line height with some padding
			float lineHeight = prntFont.GetHeight(e.Graphics) + 2;

			//set the drawing to the top left of the page
			float yPos = topMargin;
			float xPos = leftMargin;

			//print page #
			string page = "Page " + this._page;
			PrintingUtils.PrintCenter(page, e, prntFont, pageBottom - lineHeight);

			//print title			
			PrintingUtils.PrintCenter("Core Lab - Import Nano Results", e, titleFont, yPos);
			yPos += titleFont.GetHeight(e.Graphics) + 2;

			sb.Append("File: " + Path.GetFileName(_currentFile));
			sb.Append(" - Date: " + DateTime.Today.ToShortDateString());
			PrintingUtils.PrintCenter(sb.ToString(), e, subTitleFont, yPos);
			yPos += subTitleFont.GetHeight(e.Graphics) + 2;

			yPos += lineHeight;
			RectangleF rec = new RectangleF();

			lineHeight = prntFont.GetHeight(e.Graphics) + 18;
			//get the number of lines we can print
			int maxLines = (int)Math.Ceiling((double)((pageBottom - yPos) / lineHeight));
			maxLines -= 2;
			int curLine = 0;

			StringFormat fmt = new StringFormat();
			fmt.Trimming = StringTrimming.EllipsisCharacter;

			string line = "";
			for (int i = _startRow; i < _alLines.Count; i++)
			{
				if (curLine == maxLines)
				{
					_startRow = i;
					this._page++;
					e.HasMorePages = true;
					return;
				}

				line = _alLines[i].ToString();
				PrintingUtils.SetRectangle(ref rec, 0, yPos, lineHeight, pageWidth);
				gfx.DrawString(line, prntFont, Brushes.Black, rec, fmt);
				yPos += lineHeight;
				curLine++;
			}

		}
	}
}
